package com.zingrow.web.user.shiro;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.zingrow.web.user.model.ActiveUser;
import com.zingrow.web.user.model.Permission;
import com.zingrow.web.user.model.User;
import com.zingrow.web.user.service.IPermissionService;
import com.zingrow.web.user.service.IUserService;

@Service
public class MonitorRealm extends AuthorizingRealm {
	@Lazy(true)
    @Autowired
    private IUserService userService;
	@Lazy(true)
	@Autowired
    private IPermissionService permissionService;
    
	public MonitorRealm() {
        super();

    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        /* 这里编写授权代码 */

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        return simpleAuthorizationInfo;

    }

    // 用于认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
            throws AuthenticationException {
        /* 认证代码 */
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        // String password = new String((char[]) token.getPassword()); // 得到密码

     // 处理session
//        DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
//        DefaultWebSessionManager sessionManager = (DefaultWebSessionManager) securityManager.getSessionManager();
//        Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();// 获取当前已登录的用户session列表
//        Session nativeSession = null;
//        for (Session s : sessions) {
//            // 清除该用户以前登录时保存的session
//            System.out.println(token.getUsername() + "--"
//                    + String.valueOf(s.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)));
//            if (token.getUsername()
//                    .equals(String.valueOf(s.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY)))) {
//                // sessionManager.getSessionDAO().delete(s);
//                nativeSession = s;
//            }
//        }
        
        // User user = userService.checkUserLogin(token.getUsername(),
        // password);
        // if (user == null) {
        // return null;
        // }

        User user = userService.checkUserName(token.getUsername());
        if (user == null) {
            return null;
        }

        List<Permission> permission = permissionService.selectbyId(user.getPermissionId());

        // activeUser就是用户身份信息
        ActiveUser activeUser = new ActiveUser();

        activeUser.setUserId(user.getUserId());
        activeUser.setUserAccount(user.getUserAccount());
        activeUser.setUserPwd(user.getUserPwd());
        activeUser.setMenus(permission);
        activeUser.setUserType(user.getUserType());

        // WEB用户该值为空
        if (user.getSingleLogin() != null || !"".equals(user.getSingleLogin())) {
            activeUser.setSingleLogin(user.getSingleLogin());
        }

        return new SimpleAuthenticationInfo(activeUser, user.getUserPwd(), this.getName());

    }

    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

}
